package com.xiang;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifSubIFDDirectory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xiang on 30/05/2017
 */
public class PhotoSorter {
    private String inPath;
    private String outPath;
    private File inDir;
    private File outputDir;
    private List<File> importFiles;
    private List<File> errors;
    private SimpleDateFormat sdf;

    public PhotoSorter(String inPath, String outPath) {
        this.inPath = inPath;
        this.outPath = outPath;
        importFiles = new ArrayList<File>();
        errors = new ArrayList<File>();
        sdf = new SimpleDateFormat("yyyy-MM");
        this.inDir = new File(this.inPath);
        outputDir = new File(this.outPath);
    }

    public List<File> sort() {
        readFiles(inDir);
        //输出到目标位置
        if (!outputDir.exists()) {
            boolean mk = outputDir.mkdir();
            if (!mk) {
                System.out.println("创建输出文件夹失败");
                return errors;
            }
        }
        for (File file : this.importFiles) {
            try {
                putToDir(file);
            } catch (Exception e) {
                errors.add(file);
            }
        }
        return errors;
    }

    public void showErrors() {
        System.out.println("错误文件列表:" + errors.size() + "个");
        for (File file : errors) {
            System.out.println(file.getAbsolutePath());
        }
    }

    public void clearInputIdr() {

        clearDir(inDir);
    }

    private void clearDir(File dir) {
        if(!dir.isDirectory()){
            return;
        }
        File[] files = dir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return !pathname.getName().endsWith("DS_Store");
            }
        });
        if (files != null && files.length > 0) {
            for (File file : files) {
                if (file.isDirectory()){
                    clearDir(file);
                }
            }
        }else {
            dir.delete();
        }
    }

    /**
     * 把文件放到合适的文件夹
     */
    private void putToDir(File file) throws ImageProcessingException, IOException {
        Date date = getOriginalDate(file);
        if (date == null) {
            date = getLastModifiedDate(file);
        }
        if (date == null) {
            date = getFileModifiedDate(file);
        }
        String subPath = outPath + "/" + sdf.format(date);
        File subDir = new File(subPath);
        if (!subDir.exists()) {
            boolean mk = subDir.mkdir();
            if (!mk) {
                errors.add(file);
                return;
            }
        }
        moveFile(file, subDir);
    }

    private Date getOriginalDate(File file) {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(file);
            ExifSubIFDDirectory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            return directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL, TimeZone.getTimeZone("Asia/Shanghai"));
        } catch (Exception e) {
            return null;
        }
    }

    private Date getLastModifiedDate(File file) {
        return null;
    }

    /**
     * 获取文件修改时间
     */
    private Date getFileModifiedDate(File file) {
        return new Date(file.lastModified());
    }

    /**
     * 移动单个文件
     */
    private void moveFile(File file, File dir) {
        boolean result = true;
        try {
            //处理重名照片
            File exist = new File(dir.getAbsolutePath() + "/" + file.getName());
            if (exist.exists()) {
                if (!file.renameTo(new File(newName(dir.getAbsolutePath() + "/" + file.getName(), "-" + System.currentTimeMillis())))) {
                    result = false;
                }
            } else {
                if (!file.renameTo(exist)) {
                    result = false;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        if (result) {
            System.out.println(file.getName() + " is moved successful!");
        } else {
            System.out.println(file.getName() + " is failed to move!");
        }
    }

    private String newName(String filename, String plus) {
        int index = filename.lastIndexOf(".");
        String first = filename.substring(0, index);
        String end = filename.substring(index);
        return first + plus + end;
    }

    private String getSuffix(String filename) {
        int index = filename.lastIndexOf(".");
        return filename.substring(index);
    }

    /**
     * 读取文件，如果是文件夹，读取文件夹里的文件
     */
    private void readFiles(File dir) {

        File[] files = dir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return !pathname.getName().endsWith("DS_Store");
            }
        });
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (file.isFile()) {
                this.importFiles.add(file);
            }
            if (file.isDirectory()) {
                readFiles(file);
            }
        }
    }

    public String getInPath() {
        return inPath;
    }

    public String getOutPath() {
        return outPath;
    }

    public List<File> getImportFiles() {
        return importFiles;
    }
}
